const mongoose = require("./db");

//物料信息
const materialSchema = new mongoose.Schema({
  name: { type: String, required: true }, // 物料名称
  code: { type: String, required: true, unique: true }, // 物料编码
  model: { type: String }, // 型号
  unit: { type: String, required: true }, // 单位：个、kg、m等
  safeStock: { type: Number }, // 安全库存量
  isActive: { type: Boolean, default: true },// 是否启用
  images: { type: String }, // 物料图片
  description: { type: String }, // 物料描述
  createdAt: { type: Date, default: Date.now }, // 创建时间
  updatedAt: { type: Date, default: Date.now }, // 更新时间
  type: { type: String }, // 物料类型：原材料、成品
});

const Material = mongoose.model("materials", materialSchema, "materials");

//仓库信息
const warehouseSchema = new mongoose.Schema({
  name: { type: String, required: true, unique: true }, // 仓库名称
  code: { type: String, required: true, unique: true }, // 仓库编码
  location: { type: String }, // 仓库位置
  capacity: { type: Number }, // 仓库容量
  description: { type: String }, // 仓库描述
  isActive: { type: Boolean, default: true }, // 是否启用
  createdAt: { type: Date, default: Date.now }, // 创建时间
  updatedAt: { type: Date, default: Date.now }, // 更新时间
});

const Warehouse = mongoose.model("warehouses", warehouseSchema, "warehouses");

// 货架信息
const storageLocationSchema = new mongoose.Schema({
  name: { type: String, required: true }, // 库位名称
  code: { type: String, required: true, unique: true }, // 库位编码
  warehouse: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Warehouse",
    required: true,
  }, // 所属仓库
  capacity: { type: Number }, // 库位容量
  description: { type: String }, // 库位描述
  isActive: { type: Boolean, default: true }, // 是否启用
  createdAt: { type: Date, default: Date.now }, // 创建时间
  updatedAt: { type: Date, default: Date.now }, // 更新时间
});

const StorageLocation = mongoose.model(
  "storageLocations",
  storageLocationSchema,
  "storageLocations"
);

// 库存记录
const inventorySchema = new mongoose.Schema({
  material: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Material",
    required: true,
  }, // 物料
  warehouse: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Warehouse",
    required: true,
  }, // 仓库
  location: { type: mongoose.Schema.Types.ObjectId, ref: "StorageLocation" }, // 库位
  quantity: { type: Number, required: true, min: 0 }, // 数量
  batchNumber: { type: String }, // 批次号
  unitPrice: { type: Number }, // 单价
  totalValue: { type: Number }, // 总价值
  lastUpdated: { type: Date, default: Date.now }, // 更新时间
  status: {
    type: String,
    enum: ["normal", "frozen", "scrapped"],
    default: "normal",
  }, // 状态
});

const Inventory = mongoose.model("inventories", inventorySchema, "inventories");

//   库存变更记录
const inventoryTransactionSchema = new mongoose.Schema({
  material: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Material",
    required: true,
  }, // 物料
  warehouse: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Warehouse",
    required: true,
  }, // 仓库
  location: { type: mongoose.Schema.Types.ObjectId, ref: "StorageLocation" }, // 库位
  transactionType: {
    // 变更类型
    type: String,
    enum: [
      "purchase",// 采购入库
      "inbound",// 入库
      "outbound",// 出库
      "transfer",// 库存转移
      "adjustment",// 库存调整
    ],
    required: true,
  },
  quantity: { type: Number, required: true }, // 数量
  beforeQuantity: { type: Number, required: true }, // 变更前数量
  afterQuantity: { type: Number, required: true }, // 变更后数量
  referenceId: { type: mongoose.Schema.Types.ObjectId }, // 关联单据ID
  referenceType: { type: String }, // 关联单据类型
  operator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  }, // 操作人
  transactionTime: { type: Date, default: Date.now }, // 变更时间
  remarks: { type: String }, // 备注
});

const InventoryTransaction = mongoose.model(
  "inventoryTransactions",
  inventoryTransactionSchema,
  "inventoryTransactions"
);

//采购申请
const purchaseRequestSchema = new mongoose.Schema({
  requestNumber: { type: String, required: true, unique: true }, // 采购申请单号
  requester: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  }, // 申请人
  department: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Department",
    required: true,
  }, // 申请部门
  requestDate: { type: Date, default: Date.now }, // 申请日期
  expectedDeliveryDate: { type: Date }, // 预计到货日期
  purpose: { type: String }, // 用途说明
  status: {
    // 状态
    type: String,
    enum: [
      "draft", // 草稿
      "pending", // 待审批
      "approved", // 已审批
      "rejected", // 已驳回
      "processing", // 处理中
      "completed", // 已完成
      "cancelled", // 已取消
    ],
    default: "draft",
  },
  totalAmount: { type: Number, default: 0 }, // 总金额
  remarks: { type: String }, // 备注
  createdAt: { type: Date, default: Date.now }, // 创建时间
  updatedAt: { type: Date, default: Date.now }, // 更新时间
});

const PurchaseRequest = mongoose.model(
  "purchaseRequests",
  purchaseRequestSchema,
  "purchaseRequests"
);

// 采购明细
const purchaseRequestItemSchema = new mongoose.Schema({
  request: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "PurchaseRequest",
    required: true,
  }, // 采购申请单
  material: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Material",
    required: true,
  }, // 物料
  quantity: { type: Number, required: true, min: 1 }, // 数量
  estimatedPrice: { type: Number }, // 预计单价
  estimatedAmount: { type: Number }, // 预计总价
  requiredDate: { type: Date }, // 需求日期
  remarks: { type: String }, // 备注
});

const PurchaseRequestItem = mongoose.model(
  "purchaseRequestItems",
  purchaseRequestItemSchema,
  "purchaseRequestItems"
);

//   采购订单
const purchaseOrderSchema = new mongoose.Schema({
  orderNumber: { type: String, required: true, unique: true }, // 采购订单号
  request: { type: mongoose.Schema.Types.ObjectId, ref: "PurchaseRequest" }, // 采购申请单
  supplier: String, // 供应商
  orderDate: { type: Date, default: Date.now }, // 订单日期
  expectedDeliveryDate: { type: Date }, // 预计到货日期
  deliveryAddress: { type: String }, // 送货地址
  paymentTerms: { type: String }, // 付款条件
  taxRate: { type: Number, default: 0 }, // 税率
  totalAmount: { type: Number, default: 0 }, // 总金额
  taxAmount: { type: Number, default: 0 }, // 税额
  totalAmountWithTax: { type: Number, default: 0 }, // 含税总金额
  status: {
    type: String,
    enum: [
      "draft", // 草稿
      "pending", // 待审批
      "approved", // 已审批
      "rejected", // 已驳回
      "processing", /// 处理中
      "partially_received", // 部分到货
      "completed", // 已完成
      "cancelled", // 已取消
    ],
    default: "draft",
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  }, // 创建人
  remarks: { type: String }, // 备注
  createdAt: { type: Date, default: Date.now }, // 创建时间
  updatedAt: { type: Date, default: Date.now }, // 更新时间
});

const PurchaseOrder = mongoose.model(
  "purchaseOrders",
  purchaseOrderSchema,
  "purchaseOrders"
);

//   采购订单明细
const purchaseOrderItemSchema = new mongoose.Schema({
  order: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "PurchaseOrder",
    required: true,
  }, // 采购订单
  material: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Material",
    required: true,
  }, // 物料
  quantity: { type: Number, required: true, min: 1 }, // 数量
  unitPrice: { type: Number, required: true }, // 单价
  amount: { type: Number, required: true }, // 总价
  receivedQuantity: { type: Number, default: 0 }, // 已收数量
  remainingQuantity: { type: Number }, // 剩余数量
  expectedDeliveryDate: { type: Date }, // 预计到货日期
  remarks: { type: String }, // 备注
});

const PurchaseOrderItem = mongoose.model(
  "purchaseOrderItems",
  purchaseOrderItemSchema,
  "purchaseOrderItems"
);

purchaseOrderItemSchema.pre("save", function (next) {
  // 计算总价和剩余数量
  this.amount = this.quantity * this.unitPrice; // 总价
  this.remainingQuantity = this.quantity - this.receivedQuantity; // 剩余数量
  next();
});

// 入库单
const inboundOrderSchema = new mongoose.Schema({
  orderNumber: { type: String, required: true, unique: true }, // 入库单号
  purchaseOrder: { type: mongoose.Schema.Types.ObjectId, ref: "PurchaseOrder" }, // 采购订单
  inboundType: {
    // 入库类型
    type: String,
    enum: ["purchase", "return", "transfer", "adjustment", "other"],
    required: true,
  },
  warehouse: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Warehouse",
    required: true,
  }, // 仓库
  supplier: String, // 供应商
  inboundDate: { type: Date, default: Date.now }, // 入库日期
  inspector: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, // 验收人
  status: {
    type: String,
    enum: ["draft", "pending", "processing", "completed", "cancelled"],
    default: "draft",
  },// 状态
  totalQuantity: { type: Number, default: 0 }, // 总数量
  totalAmount: { type: Number, default: 0 }, // 总金额
  remarks: { type: String }, // 备注
  createdAt: { type: Date, default: Date.now }, // 创建时间
  updatedAt: { type: Date, default: Date.now }, // 更新时间
});

const InboundOrder = mongoose.model(
  "inboundOrders",
  inboundOrderSchema,
  "inboundOrders"
);

// 入库单明细
const inboundOrderItemSchema = new mongoose.Schema({
  inboundOrder: {
    // 入库单
    type: mongoose.Schema.Types.ObjectId,
    ref: "InboundOrder",
    required: true,
  },
  purchaseOrderItem: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "PurchaseOrderItem",
  }, // 采购订单明细
  material: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Material",
    required: true,
  }, // 物料
  quantity: { type: Number, required: true, min: 1 }, // 数量
  unitPrice: { type: Number, required: true }, // 单价
  amount: { type: Number, required: true }, // 总价
  batchNumber: { type: String }, // 批次号
  productionDate: { type: Date }, // 生产日期
  expiryDate: { type: Date }, // 过期日期
  location: { type: mongoose.Schema.Types.ObjectId, ref: "StorageLocation" }, // 存放库位
  inspectedQuantity: { type: Number }, // 已验收数量
  inspectedResult: {
    type: String,
    enum: ["qualified", "unqualified", "partial_qualified"],
  }, // 验收结果
  status: {
    type: String,
    enum: ["pending", "inspected", "stored"],
    default: "pending",
  }, // 状态
  remarks: { type: String }, // 备注
});

inboundOrderItemSchema.pre("save", function (next) {
  this.amount = this.quantity * this.unitPrice; // 总价
  next();
});
const InboundOrderItem = mongoose.model(
  "inboundOrderItems",
  inboundOrderItemSchema,
  "inboundOrderItems"
);

//聊天室所有数据结构
const userSchema = new mongoose.Schema({
  name: {
      type: String,
      required: true,
      trim: true,
  },
  avatar: {
      type: String,
      trim: true,
      default: 'https://example.com/default-avatar.jpg',//默认头像
  },
  email: {
      type: String,
      unique: true,
      trim: true,
      lowercase: true,
      required: true,
  },
  online: {
      type: Boolean,
      default: false,//是否在线
  },
  lastActive: {
      type: Date,
      default: Date.now,//最后活跃时间
  },
  peerId: {
      type: String,
      unique: true,
      sparse: true, // 允许为空，部分用户可能未初始化 PeerJS
  },
  createdAt: {
      type: Date,
      default: Date.now,
  },
});
// 聊天记录
const messageSchema = new mongoose.Schema({
  sender: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user',
      required: true,
  },
  receiver: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user',
      required: true,
  },
  conversation: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'conversation',
      required: true,
  },
  content: {
      type: String,
      required: function () {
          return this.type === 'text';
      },
  },
  type: {
      type: String,
      enum: ['text', 'image', 'audio', 'video', 'file','call'],
      default: 'text',
  },
  file: {
      url: String,
      name: String,
      size: String,
      mimeType: String,
  },
  isRead: {
      type: Boolean,
      default: false,
  },
  time: {
      type: Date,
      default: Date.now,
  },
});
//分组两个用户之间的消息，并存储元数据，如最后消息和未读计数。
const conversationSchema = new mongoose.Schema({
  participants: [   //参与的俩个用户的id
      {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'user',
          required: true,
      },
  ],
  lastMessage: {   //最后一条消息的id
      type: mongoose.Schema.Types.ObjectId,
      ref: 'message',
  },
  unreadCounts: [
      {
          user: {
              type: mongoose.Schema.Types.ObjectId,
              ref: 'user',
          },
          count: {
              type: Number,
              default: 0,
          },
      },
  ],
  updatedAt: {
      type: Date,
      default: Date.now,
  },
});
// 通话记录
const callSchema = new mongoose.Schema({
  conversation: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'conversation',
      required: true,
  },
  initiator: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user',
      required: true, // 通话发起者
  },
  participants: [
      {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'user',
          required: true,
      },
  ],
  type: {
      type: String,
      enum: ['video', 'audio'],
      required: true, // 通话类型：视频或语音
  },
  status: {
      type: String,
      enum: ['initiated', 'connected', 'ended', 'missed', 'declined'],
      default: 'initiated', // 通话状态
  },
  startTime: {
      type: Date,
  },
  endTime: {
      type: Date,
  },
  duration: {
      type: Number, // 通话时长（秒）
  },
  recording: {
      url: String, // 可选的通话录音或录像 URL
      size: String,
      mimeType: String,
  },
  createdAt: {
      type: Date,
      default: Date.now,
  },
});
//共享文件
const sharedFileSchema = new mongoose.Schema({
  conversation: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'conversation',
      required: true,
  },
  uploader: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user',
      required: true,
  },
  name: {
      type: String,
      required: true,
  },
  type: {
      type: String,
      enum: ['image', 'video', 'document', 'other','file'],
      required: true,
  },
  url: {
      type: String,
      required: true,
  },
  size: {
      type: String,
      required: true,
  },
  mimeType: {
      type: String,
  },
  uploadedAt: {
      type: Date,
      default: Date.now,
  },
});
let userModel = mongoose.model('user', userSchema, 'user')
let messageModel = mongoose.model('message', messageSchema, 'message')
let conversationModel = mongoose.model('conversation', conversationSchema, 'conversation')
let callModel = mongoose.model('call', callSchema, 'call')
let sharedFileModel = mongoose.model('file', sharedFileSchema, 'file')



module.exports = {
  Material,
  Warehouse,
  StorageLocation,
  userModel,
  messageModel,
  conversationModel,
  callModel,
  sharedFileModel,
  Inventory,
  InventoryTransaction,
  PurchaseRequest,
  PurchaseRequestItem,
  PurchaseOrder,
  PurchaseOrderItem,
  InboundOrder,
  InboundOrderItem,
};
